package com.sgj.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * @Author: Guoji Shen
 * @Date: 2021/8/10 11:04
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        // 创建线程放数据
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                myCache.put(num + "", num + "");
            }, String.valueOf(i)).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 创建线程取数据
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                myCache.get(num + "");
            }, String.valueOf(i)).start();
        }
    }
}

class MyCache {

    /**
     * 创建Map集合
     */
    private volatile Map<String, Object> map = new HashMap<>();

    private ReadWriteLock rwLock = new ReentrantReadWriteLock();

    // 存放数据
    public void put(String key, Object value) {

        // 添加写锁
        Lock lock = rwLock.writeLock();
        // 上锁
        lock.lock();

        try {
            System.out.println(Thread.currentThread().getName() + " 正在进行写操作, key:" + key);
            // 暂停一会
            TimeUnit.MICROSECONDS.sleep(300);
            // 放数据
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + " 写完了, key:" + key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }

    }

    // 取数据
    public Object get(String key) {

        Object result = null;

        // 添加读锁
        Lock lock = rwLock.readLock();
        // 上锁
        lock.lock();

        try {
            System.out.println(Thread.currentThread().getName() + " 正在进行读取操作, key:" + key);
            // 暂停一会
            TimeUnit.MICROSECONDS.sleep(300);
            // 取出数据
            result = map.get(key);
            System.out.println(Thread.currentThread().getName() + " 取完了, key:" + key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }

        return result;
    }
}